package com.magicborrow.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.adapter.SchoolAdapter;
import com.magicborrow.beans.BaseEntity;
import com.magicborrow.beans.SchoolEntity;
import com.magicborrow.beans.StringEntity;
import com.magicborrow.beans.UserBean;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.LoadingDialog;

import java.util.HashMap;
import java.util.List;

/**
 * Created by ronaldo on 2016/6/8.
 */
public class SchoolListActivity extends BaseActivity implements VolleyTool.HTTPListener {

    private TextView tvSchool;
    private ImageView ivArrow;
    private PopupWindow popupWindow;

    private boolean isArrowTop=false;
    private View schoolView;
    private LinearLayout llSearchOutside;
    private LinearLayout llSearch;
    private EditText etSchool;
    private RecyclerView mRecyclerView;
    private SchoolAdapter schoolAdapter;
    private ImageView ivRefrshImg;
    private UserBean.User user;

    private EditText etStuNumber;
    private EditText etStuPwd;
    private EditText etStuCode;
    private LoadingDialog loadingDialog;
    private long schoolCode=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schoollist);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        tvSchool = (TextView) findViewById(R.id.tv_school);
        ivArrow = (ImageView) findViewById(R.id.iv_arrow);
        ivRefrshImg = (ImageView) findViewById(R.id.iv_refrsh_img);

        etStuNumber = (EditText) findViewById(R.id.et_stu_number);
        etStuPwd = (EditText) findViewById(R.id.et_stu_pwd);
        etStuCode = (EditText) findViewById(R.id.et_stu_code);

        schoolView = View.inflate(this, R.layout.schoolview, null);
        mRecyclerView = (RecyclerView) schoolView.findViewById(R.id.recyclerView);
        llSearchOutside = (LinearLayout) schoolView.findViewById(R.id.ll_search_outside);
        llSearch = (LinearLayout) schoolView.findViewById(R.id.ll_search);
        etSchool = (EditText) schoolView.findViewById(R.id.et_school);
    }

    private void initData() {
        loadingDialog = new LoadingDialog(this);
        user = UserTools.getUser(this);
        schoolAdapter = new SchoolAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(schoolAdapter);
        sendRequest("");
    }

    private void sendRequest(String text) {
        HashMap<String, String> params = new HashMap<>();
        params.put("key",text);
        VolleyTool.get(Constants.URL_GET_SCHOOLLIST,params,this, Constants.REQUEST_ONE,SchoolEntity.class);
    }

    private void initListener() {
        findViewById(R.id.ll_sel_school).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aboutPopwindow(view);
            }
        });
        findViewById(R.id.iv_refreshcode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getImageCode(schoolCode);
            }
        });
        etSchool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llSearchOutside.setGravity(Gravity.LEFT);
            }
        });
        etSchool.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                if (charSequence.length()<=0) {
                    return;
                }
                searchSchool();
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        schoolAdapter.setOnClickSchoolListener(new SchoolAdapter.OnClickSchoolListener() {
            @Override
            public void onClickSchool(String selText,long selId) {
                tvSchool.setText(selText);
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                getImageCode(selId);
            }
        });
        findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm();
            }
        });
    }

    //确定提交
    private void confirm() {
        String stuNumber= etStuNumber.getText().toString();
        String stuPwd= etStuPwd.getText().toString();
        String stuCode= etStuCode.getText().toString();
        if (TextUtils.isEmpty(stuNumber)){
            showShortMsg("学号不可以为空");
            return;
        }
        if (TextUtils.isEmpty(stuPwd)){
            showShortMsg("校园网账号不可以为空");
            return;
        }
//        if (TextUtils.isEmpty(stuCode)){
//            showShortMsg("验证码不可以为空");
//            return;
//        }
        if (schoolCode==0){
            showShortMsg("请选择学校名称");
            return;
        }
        loadingDialog.show();
        HashMap<String, String> params = new HashMap<>();
        params.put("acc_token", user.getAcc_token());
        params.put("schoolId", schoolCode+"");
        params.put("loginName",stuNumber);
        params.put("password", stuPwd);
        if(!TextUtils.isEmpty(stuCode)){
            params.put("captcha",stuCode);
        }else{
            params.put("captcha","");
        }
        VolleyTool.get(Constants.URL_GET_STUCODE,params,this, Constants.REQUEST_THREE,BaseEntity.class);
    }

    private void getImageCode(long selId) {
        if (selId==0){
            showShortMsg("请先选择学校");
            return;
        }
        System.out.println("selId："+selId);
        schoolCode=selId;
        HashMap<String, String> params = new HashMap<>();
        params.put("acc_token", user.getAcc_token());
        params.put("schoolId",selId+"");
        VolleyTool.get(Constants.URL_GET_IMAGECODE,params,this, Constants.REQUEST_TWO,StringEntity.class);
    }

    private void searchSchool() {
        sendRequest(etSchool.getText().toString().trim());
    }

    private void aboutPopwindow(View view) {
        popupWindow = new PopupWindow(schoolView,ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
        popupWindow.setFocusable(true);
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            ivArrow.setBackgroundResource(R.mipmap.arrow_bottom);
        } else {
            popupWindow.showAsDropDown(view);
            ivArrow.setBackgroundResource(R.mipmap.arrow_top);
        }
    }

    @Override
    public void onBackPressed() {
        if(!getDissWindow()){
            super.onBackPressed();
        }
    }

    public boolean getDissWindow() {
        if (popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
            return true;
        }
        return false;
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (requestCode==Constants.REQUEST_ONE){
            SchoolEntity entity= (SchoolEntity) t;
            List<SchoolEntity.SchoolData> data = entity.getData();
            if (data!=null)
                schoolAdapter.setData(data);
                schoolAdapter.notifyDataSetChanged();
        }else if (requestCode==Constants.REQUEST_TWO){
            StringEntity entity= (StringEntity) t;
            String data = entity.getData();
            if (null==data){
                etStuCode.setHint("所选学校不需要输入验证码");
                etStuCode.setEnabled(false);
                ivRefrshImg.setVisibility(View.GONE);
                return;
            }else{
                etStuCode.setHint("请输入验证码");
                etStuCode.setEnabled(true);
                ivRefrshImg.setVisibility(View.VISIBLE);
            }
//            System.out.println("http:"+data);
            VolleyTool.getImageLoader().get(data, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    if (response.getBitmap()!=null){
                        ivRefrshImg.setImageBitmap(response.getBitmap());
                    }
                }
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
        }else if (requestCode==Constants.REQUEST_THREE){
            BaseEntity entity= (BaseEntity) t;
            if (entity.getCode()==0){
                finish();
                MagicBorrowApplication.getInstance().setPass(true);
            }else{
                showShortMsg(entity.getMessage());
            }
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        loadingDialog.dismiss();
    }
}
